package com.design.patterns.list.prototype.up;

import java.io.*;

/**
 * @author Wangzhiwen
 */
public class DeepClone implements Cloneable, Serializable {

    private String clone;

    private String age;

    private DeepCloneTarget target;

    public DeepClone(String clone, String age, DeepCloneTarget target) {
        this.clone = clone;
        this.age = age;
        this.target = target;
    }

    public DeepCloneTarget getTarget() {
        return target;
    }

    public void setTarget(DeepCloneTarget target) {
        this.target = target;
    }

    public String getClone() {
        return clone;
    }

    public void setClone(String clone) {
        this.clone = clone;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    // 深拷贝方式一
    @Override
    public Object clone() throws CloneNotSupportedException {
        // 先对自己进行拷贝
        DeepClone clone = (DeepClone) super.clone();
        // 在对引用类型进行拷贝
        clone.target = target = (DeepCloneTarget) clone.target.clone();
        // 赋值

        return clone;
    }

    // 深拷贝方式二，反序列化对象
    public Object deepClone() throws CloneNotSupportedException {
        try(
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);

        ) {
            // 序列化
            objectOutputStream.writeObject(this);
            // 反序列化
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

            return objectInputStream.readObject();
        }catch (Exception e){
            throw new CloneNotSupportedException();
        }
    }

    @Override
    public String toString() {
        return "DeepClone{" +
                "clone='" + clone + '\'' +
                ", age='" + age + '\'' +
                '}';
    }
}
